package com.akk.utils.lecturer;

import com.akk.module.avs.entity.AvsLecturer;
import com.akk.module.upload.utils.FtpUtil;
import com.akk.utils.IDUtils;
import com.akk.utils.QRCodeEvents;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

@Service
public class CompositeImage {

    @Value("${ftp.address}")
    private String FTP_ADDRESS;
    @Value("${ftp.port}")
    private Integer FTP_PORT;
    @Value("${ftp.username}")
    private String FTP_USERNAME;
    @Value("${ftp.password}")
    private String FTP_PASSWORD;
    @Value("${ftp.base.path}")
    private String FTP_BASE_PATH;
    @Value("${image.base.url}")
    private String IMAGE_BASE_URL;

//    private Font font = new Font("CTBiaoSongSJ", Font.BOLD, 20);// 添加字体的属性设置

    private Graphics g = null;

    private int fontsize = 0;

    private int x = 0;

    private int y = 0;

    /**
     * 导入本地图片到缓冲区
     */
    public BufferedImage loadImageLocal(File file) {
        try {
            return ImageIO.read(file);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 导入网络图片到缓冲区
     */
    public BufferedImage loadImageUrl(String imgName) {
        try {
            URL url = new URL(imgName);
            return ImageIO.read(url);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 生成新图片到本地
     */
    public void writeImageLocal(String newImage, BufferedImage img) {
        if (newImage != null && img != null) {
            try {
                File outputfile = new File(newImage);
                ImageIO.write(img, "png", outputfile);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * 设定文字的字体等
     */
    public void setFont(String fontStyle, int fontSize) {
        this.fontsize = fontSize;
//        this.font = new Font(fontStyle, Font.PLAIN, fontSize);
    }

    /**
     * 修改图片,返回修改后的图片缓冲区（只输出一行文本）
     */
    public BufferedImage modifyImage(BufferedImage img, Object content, int x, int y,Font font,Color color) {
        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
//            g.setBackground(Color.WHITE);
            g.setColor(color);//设置字体颜色
            g.setFont(font);
            // 验证输出位置的纵坐标和横坐标
            if (x >= h || y >= w) {
                this.x = h - this.fontsize + 2;
                this.y = w;
            } else {
                this.x = x;
                this.y = y;
            }
            if (content != null) {
                g.drawString(content.toString(), this.x, this.y);
            }
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return img;
    }

    /**
     * 修改图片,返回修改后的图片缓冲区（输出多个文本段） xory：true表示将内容在一行中输出；false表示将内容多行输出
     */
    public BufferedImage modifyImage(BufferedImage img, Object[] contentArr, int x, int y, boolean xory,Font font,Color color) {
        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
//            g.setBackground(Color.WHITE);
            g.setColor(color);
            g.setFont(font);
            // 验证输出位置的纵坐标和横坐标
            if (x >= h || y >= w) {
                this.x = h - this.fontsize + 2;
                this.y = w;
            } else {
                this.x = x;
                this.y = y;
            }
            if (contentArr != null) {
                int arrlen = contentArr.length;
                if (xory) {
                    for (int i = 0; i < arrlen; i++) {
                        g.drawString(contentArr[i].toString(), this.x, this.y);
                        this.x += contentArr[i].toString().length()
                                * this.fontsize / 2 + 5;// 重新计算文本输出位置
                    }
                } else {
                    for (int i = 0; i < arrlen; i++) {
                        g.drawString(contentArr[i].toString(), this.x, this.y);
                        this.y += this.fontsize + 2;// 重新计算文本输出位置
                    }
                }
            }
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return img;
    }


    public BufferedImage modifyImagetogeter(BufferedImage bg, BufferedImage zhang,int x,int y,int width,int height) {
        try {
            Graphics g = bg.getGraphics();
            g.drawImage(zhang, x, y, width, height, null);
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return bg;
    }

    public String certificate(AvsLecturer entity){
        if (entity.getFileUrl() != null && entity.getFileUrl().length() > 1)
            return entity.getFileUrl();
//        File bgFile = new File(Resources.getResource("static/public/lecture/bg.png").getFile());
//        File zhangFile = new File(Resources.getResource("static/public/lecture/zhang.png").getFile());
        BufferedImage bg = this.loadImageUrl("http://www.028wkf.cn/public/lecture/bg.png");
        BufferedImage zhang = this.loadImageUrl("http://www.028wkf.cn/public/lecture/zhang.png");
        BufferedImage photo = this.loadImageUrl(entity.getPhotoUrl());
        if ( bg == null || zhang == null || photo == null)
            return null;
//        BufferedImage image = this.modifyImage(bg,entity.getName(),1570,1125,new Font("CTBiaoSongSJ",Font.PLAIN,80),Color.black);

        Graphics graphics = bg.getGraphics();
        graphics.setFont(new Font("CTBiaoSongSJ",Font.PLAIN,80));
        graphics.setColor(Color.black);
        graphics.drawString(entity.getName(),1570,1125);
        graphics.setColor(new Color(35, 35, 35));
        graphics.setFont(new Font("CTBiaoSongSJ",Font.PLAIN,70));
        String type = "";
        switch (entity.getType()){
            case 1:
                // 初级
                type = "初";
                break;
            case 2:
                // 中级
                type = "中";
                break;
            case 3:
                // 高级
                type = "高";
                break;
            case 4:
                // 专家
                type = "专家";
                break;
        }
        graphics.drawString(type,2045,1429);
        if (entity.getCompany().length() > 5){
            String str1 = entity.getCompany().substring(0,4);
            String str2 = entity.getCompany().substring(4,entity.getCompany().length());
            graphics.drawString( str1,2865,1429);
            graphics.drawString(str2,1525,1565);
        }else {
            graphics.drawString(entity.getCompany(),1525,1565);
        }
        graphics.setFont(new Font("CTBiaoSongSJ",Font.PLAIN,60));
        graphics.drawString(entity.getCertificateNumber(),2049,1943);
        graphics.drawString(entity.getIdCard(),2049,1830);
        graphics.setFont(new Font("CTBiaoSongSJ",Font.PLAIN,50));
        Calendar start = Calendar.getInstance();
        start.setTime(entity.getStartTime());
        graphics.drawString(String.valueOf(start.get(Calendar.YEAR)),2155,2126);
        graphics.drawString(String.valueOf(start.get(Calendar.MONTH) + 1),2370,2126);
        graphics.drawString(String.valueOf(start.get(Calendar.DAY_OF_MONTH)),2495,2126);
        Calendar end = Calendar.getInstance();
        end.setTime(entity.getEndTime());
        graphics.drawString(String.valueOf(end.get(Calendar.YEAR)),2790,2126);
        graphics.drawString(String.valueOf(end.get(Calendar.MONTH) + 1),2995,2126);
        graphics.drawString(String.valueOf(end.get(Calendar.DAY_OF_MONTH)),3110,2126);
        graphics.drawImage(photo,2895,770,305,415,null);
        graphics.drawImage(zhang,2657,1849,350,350,null);
        String newName = IDUtils.genImageName();
        newName = newName + ".png";
        String imagePath = new DateTime().toString("/yyyy/MM/dd");
        String imageUrl = IMAGE_BASE_URL + imagePath + "/" + newName;
        BufferedImage qrCode = QRCodeEvents.createQRCode(imageUrl,100,100);
        // 1460 1750
        graphics.drawImage(qrCode,1460,1735,270,270,null);
        graphics.dispose();
        //this.writeImageLocal("F:\\newFile.png",bg);

        InputStream inputStream = null;
        try {
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(bg, "png", imOut);
            inputStream = new ByteArrayInputStream(bs.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (inputStream == null)
            return null;
//        图片上传
        boolean result = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD,
                FTP_BASE_PATH, imagePath, newName, inputStream);
        if (result)
            return imageUrl;
        return null;
    }

    public void inputstreamtofile(InputStream ins,File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {

        /// 证书
        AvsLecturer entity = new AvsLecturer();
        entity.setCreateDate(new Date());
        entity.setPhotoUrl("http://192.168.1.179/picture/2017/06/23/1498196216739326.jpg");
        entity.setCertificateNumber("NO.165436546186");
        entity.setIdCard("511921199508216738");
        entity.setCompany("成都爱卡卡投资咨询有限公司");
        entity.setStartTime(new Date());
        entity.setEndTime(new Date());
        entity.setType(2);
        entity.setName("老张");
        CompositeImage image = new CompositeImage();
        image.certificate(entity);

    }

}